package cn.jilian.dao.support;

import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import cn.jilian.common.dto.PageInfo;
import cn.jilian.common.dto.PageResult;
import cn.jilian.common.dto.SortInfo;
import cn.jilian.dao.PageQuery;


@Repository
public class PageQueryImpl implements PageQuery {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	@Override
	public PageResult<Map<String, Object>> query(String sql, Object[] args, PageInfo page) {
		return jsonPaginate(sql,args,page,"");
	}
	

	private int getCount(String sql,Object[] args){
		String sqlCount = "select count(*) as COUNT from ("+sql+") t";
		int total = jdbcTemplate.queryForObject(sqlCount, args,Integer.class);
		return total;
	}
	
	private PageResult<Map<String, Object>> jsonPaginate(String sql, Object[] params ,PageInfo pageInfo,String sortFilter){
		pageInfo.setTotal(getCount(sql,params));		
		long start = pageInfo.getStart();
		int limit = pageInfo.getLimit();
		int page=pageInfo.getPage();
		if(start==0&&page>0) {
			start=(page-1)*limit;
			pageInfo.setStart(start);
		}
		List<Map<String, Object>> items = null;
		if(pageInfo.getTotal()>0){
			sql += sortFilter;
			sql+=" limit ?,?";
			Object[] args=null;
			if(params==null) {
				args=new Object[]{start,limit};
			}else {
				args=new Object[params.length+2];
				System.arraycopy(params, 0, args, 0, params.length);
				args[args.length-1]=limit;
				args[args.length-2]=start;
			}
			
			items = jdbcTemplate.queryForList(sql, args);
		}else{
			items = Collections.emptyList();
		}
		pageInfo.setCache(items.size());
		PageResult<Map<String, Object>> map =  new PageResult<Map<String, Object>>(pageInfo,items);
		return map;
	}


	@Override
	public PageResult<Map<String, Object>> query(String sql, PageInfo page) {
		return  jsonPaginate(sql,new Object[] {},page,"");
	}


	@Override
	public PageResult<Map<String, Object>> query(String sql, PageInfo page, List<String> sorts) {
		return  jsonPaginate(sql,new Object[] {},page,"order by "+StringUtils.join(sorts," and "));
	}


	@Override
	public PageResult<Map<String, Object>> query(String sql, Object[] args, PageInfo page, List<String> sorts) {
		return  jsonPaginate(sql,args,page,"order by "+StringUtils.join(sorts," and "));
	}


	@Override
	public PageResult<Map<String, Object>> query(String sql, Object[] args, PageInfo page, SortInfo sortInfo) {
		String sorts="";
		if(sortInfo!=null&&StringUtils.isNotBlank(sortInfo.getField())) {
			sorts=" order by "+sortInfo.getField();
			if(StringUtils.isNotBlank(sortInfo.getDirect())){
				sorts+=" "+sortInfo.getDirect();
			}
		}
		return  jsonPaginate(sql,args,page,sorts);
	}

}
